//
//  MNDOpenDepositoryTransferViewController.m
//  minidai
//
//  Created by 容贤郁 on 2018/3/14.
//  Copyright © 2018年 迷你金服. All rights reserved.
//

#import "MNDOpenDepositoryTransferViewController.h"
#import "UIButton+JKCountDown.h"
#import "MNDDepositWebViewController.h"
#import <TTTAttributedLabel.h>
#import "MNDWebViewController.h"
#import "MNDAlertViewController.h"
#import "UIImage+JKColor.h"

@interface MNDOpenDepositoryTransferViewController () <TTTAttributedLabelDelegate>

@property (weak, nonatomic) IBOutlet UITextField *captchaTextField;
@property (weak, nonatomic) IBOutlet UIButton *sendCaptchaButton;
@property (weak, nonatomic) IBOutlet TTTAttributedLabel *protocolLabel;

@property (weak, nonatomic) IBOutlet UILabel *noticeLabel;

@property (nonatomic, copy) NSString *alertMessage;


@end

@implementation MNDOpenDepositoryTransferViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.captchaTextField.placeholder = [NSString stringWithFormat:@"请输入尾号%@收到的验证码", [self.phoneNumber substringFromIndex:self.phoneNumber.length - 4]];
    
    [self.sendCaptchaButton addTarget:self action:@selector(sendPhoneCaptcha:) forControlEvents:UIControlEventTouchUpInside];
    
    [self sendPhoneCaptcha:self.sendCaptchaButton];
    
    __block UITextField *captchaField = self.captchaTextField;
    
    [self.captchaTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if (x.length > 6) {
            captchaField.text = [x substringToIndex:6];
        }
    }];
    
    [self loadSignIntroductionMessage];
    
    [self initialBackButton];
    
    [self addAgreementLabelAttribute];
    
    if (self.messageStr.length > 0) {
        self.noticeLabel.text = self.messageStr;
    } else {
        [self loadDepositInfo];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage jk_imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    
    UIImage *image = [UIImage jk_imageWithColor:[UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:0.3]];
    [self.navigationController.navigationBar setShadowImage:image];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initialRightBarButton {
    UIImage *itemImage = [UIImage imageNamed:@"notice_help_icon"];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage: [itemImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAction:)];
    //    [item setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
}

- (void)rightBarButtonAction:(id)sender {
    if (self.alertMessage) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        MNDAlertViewController *alertController = [storyboard instantiateViewControllerWithIdentifier:[MNDAlertViewController description]];
        [KeyWindow addSubview:alertController.view];
        [self.tabBarController addChildViewController:alertController];
        
        alertController.alertTitle = @"债权转让授权说明";
        alertController.alertMessage = self.alertMessage;
    }
}

- (void)loadSignIntroductionMessage {
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_SIGN_INTRODUCTION parameters:[MNDSign signedParamWithDict:@{@"type": @"auto_transfer"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakself.alertMessage = responseModel.data[@"introductions"];
            [weakself initialRightBarButton];
        }
    } onFailure:^(NSError *error) {
        
    }];
}

- (void)loadDepositInfo {
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_GET_DEPOSIT_INFO parameters:[MNDSign signedParamWithDict:@{@"perfect_type": @"2"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseFailure) {
            NSDictionary *msgDict = responseModel.msg;
            if ([msgDict.allKeys containsObject:@"sign"]) {
                [NetworkProgressHUD hideHud];
                
                weakself.noticeLabel.text = responseModel.msg[@"error"];
            } else {
                [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            }
        } else {
//            [self backAction:nil];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)sendPhoneCaptcha:(UIButton *)sender {
    NSDictionary *params = @{@"user_phone": self.phoneNumber, @"channel": @"app", @"srvtxcode": @"autoCreditInvestAuthPlus"};

    [NetworkProgressHUD showHud];
    
    [APIManager sendRequestWithPath:API_DEPOSIT_SEND_CAPTCHA parameters:[MNDSign signedParamWithDict:params] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            [sender jk_startTime:30 title:@"重新获取" waitTittle:@"秒后重发"];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (IBAction)grantAction:(UIButton *)sender {
    if (self.captchaTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入短信验证码"];
        return;
    }
    [NetworkProgressHUD showHud];
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"smscode": self.captchaTextField.text, @"channel": @"app"}];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_DEPOSIT_TRANSACTION_GRANT parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            
            MNDDepositWebViewController *webVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositWebViewController description]];
            webVC.htmlStr = responseModel.data;
            webVC.title = @"自动债权转让授权";
            webVC.fromNaviIndex = weakself.fromNaviIndex;
            
            [weakself.navigationController pushViewController:webVC animated:YES];
            
        } else {
            [weakself loadDepositInfoWithErrorStr:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)loadDepositInfoWithErrorStr:(NSString *)errorStr {
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_GET_DEPOSIT_INFO parameters:[MNDSign signedParamWithDict:@{@"perfect_type": @"2"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseFailure) {
            NSDictionary *msgDict = responseModel.msg;
            if ([msgDict.allKeys containsObject:@"sign"]) {
                NSString *signStr = responseModel.msg[@"sign"];
                if ([signStr isEqualToString:kSignAutoTransfer]) {
                    [NetworkProgressHUD showHudMsg:errorStr];
                    
                } else {
                    [NetworkProgressHUD showHudMsg:@"您已开通存管"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [weakself backAction:nil];
                    });
                }
            } else {
                [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            }
        } else {
            [NetworkProgressHUD showHudMsg:@"您已开通存管"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakself backAction:nil];
            });
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)addAgreementLabelAttribute {
    //设置高亮颜色
    self.protocolLabel.highlightedTextColor = kColorDarkOrange;
    //检测类型
    self.protocolLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
    //代理
    self.protocolLabel.delegate = self;
    //不显示下划线
    self.protocolLabel.linkAttributes = @{(NSString *)kCTUnderlineStyleAttributeName: [NSNumber numberWithBool:NO]};
    
    NSString *text = @"点击按钮表示您同意《债权转让授权协议》";
    [self.protocolLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
        NSRange linkRange = [[mutableAttributedString string] rangeOfString:@"《债权转让授权协议》" options:NSCaseInsensitiveSearch];
        
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorDarkOrange} range:linkRange];
        
        return mutableAttributedString;
    }];
    
    NSRange linkRange = [text rangeOfString:@"《债权转让授权协议》" options:NSCaseInsensitiveSearch];
    NSURL *url = [NSURL URLWithString:kAutoTransferAccord];
    [self.protocolLabel addLinkToURL:url withRange:linkRange];
}

- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
    webVC.webViewUrl = url.absoluteString;
    webVC.loadType = LoadTypeLink;
    webVC.naviBarHidden = NO;
    
    webVC.title = @"债权转让授权协议";
    
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:webVC];
    
    [self presentViewController:navVC animated:YES completion:^{
        
    }];
}

- (void)initialBackButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

- (void)backAction:(id)sender {
    UIViewController *viewController = self.navigationController.viewControllers[self.fromNaviIndex];
    [self.navigationController popToViewController:viewController animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
